package com.ruoyi.web.controller;

import com.github.binarywang.wxpay.bean.order.WxPayMpOrderResult;
import com.github.binarywang.wxpay.bean.request.WxPayUnifiedOrderRequest;
import com.github.binarywang.wxpay.exception.WxPayException;
import com.github.binarywang.wxpay.service.WxPayService;
import com.ruoyi.common.config.wx.WxPayConfiguration;
import com.ruoyi.common.core.controller.ApiBaseController;
import com.ruoyi.common.core.domain.ApiResult;
import com.ruoyi.common.json.JSONObject;
import com.ruoyi.framework.web.domain.server.Mem;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.service.*;
import com.ruoyi.web.common.Vo.CreateOrderIVo;
import com.ruoyi.web.common.Vo.SubmitOrderIVo;
import io.swagger.annotations.Api;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.*;


/**
 * 订单管理
 */
@Api(description = "订单管理")
@Controller
@RequestMapping("/api/order")
public class ApiOrderController extends ApiBaseController {

    @Autowired
    IShopOrderService shopOrderService;

    @Autowired
    IShopOrderItemService shopOrderItemService;

    @Autowired
    IGoodsService goodsService;

    @Autowired
    IBusinessShopService businessShopService;

    @Autowired
    IShopActivityService shopActivityService;

    @Autowired
    IMemberService memberService;

    @PostMapping("/create")
    @ResponseBody
    public ApiResult create(@RequestBody CreateOrderIVo createOrderIVo)
    {
        Long goodsId = createOrderIVo.getGoodsId();
        Long shopId = createOrderIVo.getShopId();
        if(goodsId == null ||  shopId == null){
            return ApiResult.error("参数有误");
        }

        Goods goods = goodsService.selectGoodsById(goodsId);
        BusinessShop businessShop = businessShopService.selectBusinessShopById(shopId);
        if (goods == null || businessShop == null){
            return ApiResult.error("优惠券已经被下架或者删除");
        }
//        if (businessShop.getStates() == false){
//            return ApiResult.error("该商家已经下架了");
//        }

        //判断是否有库存
        Long salesNum = goods.getSales();
        Long limitNumber = goods.getLimitSale();
//        if (salesNum + 1 > limitNumber){
//            return ApiResult.error("优惠券已经被售完,下次请提早哦");
//        }

        //判断是否参加了活动。活动是否已经失效
        ShopActivity shopActivity = new ShopActivity();
        shopActivity.setRelateId(goodsId);
        shopActivity.setRelateType(0L);
        List<ShopActivity> shopActivityList = shopActivityService.selectShopActivityList(shopActivity);
        if (shopActivityList.size() > 1){ // 暂时只能一个活动 一个 商品
            return ApiResult.error("系统出现错误，请联系管理员");
        }


        //活动 按照活动量算。
        if (shopActivityList.size() == 1){
            ShopActivity tempShopActivity = shopActivityList.get(0);

            //判断活动是否已经开始 或者已经结束
            Date nowDate = new Date();
            Date beginDate = tempShopActivity.getBeginDate();
            Date endDate = tempShopActivity.getEndDate();
            Boolean isActivityStart = false;

            if (endDate != null) {  //限量活动无限时间
                if (nowDate != null && beginDate != null && endDate != null){
                    isActivityStart = belongCalendar(nowDate , beginDate, endDate);
                }
            }

            if(isActivityStart){
                //限量活动
                if (tempShopActivity.getType() == 0){
                    Long activityLimitNumber = tempShopActivity.getLimitNumber();
                    Long activitySaleNumber = tempShopActivity.getSaleNumber();
                    if (activityLimitNumber < activitySaleNumber + 1){
                        return ApiResult.error("活动已经结束,欢迎下次再来");
                    }
                }

                //TODO: 活动优惠在这里写 打折 或者 满减 后期增加
            }
        }

        Member member = memberService.getCurrentMember(getRequest());


        //创建订单
        ShopOrder shopOrder = shopOrderService.createOrder(0L,
                goods,
                businessShop,
                member.getMobile(),
                member.getNickname(),
                member
                );
        String userName = member.getNickname();
        String mobile = member.getMobile();

        JSONObject resultJson = new JSONObject();

        resultJson.put("goods",goods);
        resultJson.put("order",shopOrder);
        resultJson.put("actualTotal", shopOrder.getAmount());
        resultJson.put("total",shopOrder.getAmount());
        List<ShopOrderItem> orderItemList = shopOrder.getShopOrderItems();
        Long totalCount = Long.valueOf(0);
        for (ShopOrderItem shopOrderItem : orderItemList){
            totalCount = totalCount + shopOrderItem.getQuantity();
        }
        resultJson.put("totalCount", totalCount);
        resultJson.put("orderId", shopOrder.getId());
        resultJson.put("userName", userName);
        resultJson.put("phone", mobile);

        return ApiResult.success(resultJson);
    }


    @PostMapping("/submit")
    @ResponseBody
    public ApiResult submit(@RequestBody SubmitOrderIVo submitOrderIVo) throws UnsupportedEncodingException {
        Long orderId = submitOrderIVo.getOrderId();
        Long totalNumber = submitOrderIVo.getTotalCount();
        String phone = submitOrderIVo.getPhone();
        String userName = submitOrderIVo.getUserName();
        if (orderId == null){
            return ApiResult.error("无效的订单Id");
        }
        ShopOrder order = shopOrderService.selectShopOrderById(orderId);
        if (order == null){
            return ApiResult.error("订单不存在");
        }
        order.setConsignee(URLEncoder.encode(userName, "UTF-8"));
        order.setPhone(phone);
        //检查订单状态
        if (order.getStatus() != Long.valueOf(ShopOrder.Status.pendingPayment.ordinal())){
            return ApiResult.error("订单状态 ");
        }
        //更新订单
        ShopOrderItem shopOrderItem = new ShopOrderItem();
        shopOrderItem.setOrderId(orderId);
        List<ShopOrderItem> orderItemList = shopOrderItemService.selectShopOrderItemList(shopOrderItem);
        if (orderItemList.size() != 1){
            //现在只能是一个。 一个订单只有一个item 如果是商品订单 则允许多个
            return ApiResult.error("订单出现异常");
        }
        shopOrderItem = orderItemList.get(0);
        shopOrderItem.setQuantity(totalNumber);
        Goods goods = goodsService.selectGoodsById(shopOrderItem.getGoodsId());
        if (goods == null){
            return ApiResult.error("商品已经下架");
        }
//        Long limitSale = goods.getLimitSale();
//        if (limitSale < totalNumber){
//            return  ApiResult.error("超过限售数量,请调整购买数量");
//        }
        if (goods.getIsMarketable() == false){
            //TODO； 订单状态修改为非法 或者删除这个订单
            return ApiResult.error("商品已经下架， 请下次再来");
        }
        BigDecimal totalPrice = BigDecimal.valueOf(goods.getPrice()).multiply(BigDecimal.valueOf(totalNumber)).setScale(2,BigDecimal.ROUND_DOWN);
        order.setAmount(totalPrice.doubleValue());
        shopOrderService.updateShopOrder(order);
        shopOrderItemService.updateShopOrderItem(shopOrderItem);
        JSONObject resultObject = new JSONObject();
        resultObject.put("orderSn", order.getSn());
        return ApiResult.success(resultObject);
    }

    //获取请求参数
    @GetMapping("/pay/{sn}")
    @ResponseBody
    public ApiResult pay(@PathVariable("sn") String sn){
        if (sn == null){
            return ApiResult.error("非法参数");
        }

        ShopOrder order = shopOrderService.selectShopOrderBySn(sn);
        if (order == null){
            return ApiResult.error("订单编号错误");
        }
        if (order.getStatus() != Long.valueOf(ShopOrder.Status.pendingPayment.ordinal())){
            return ApiResult.error("订单已支付，请不要重复操作!");
        }

        Member member = memberService.getCurrentMember(getRequest());

        WxPayService wxPayService = WxPayConfiguration.wxService();
        WxPayUnifiedOrderRequest wxPayUnifiedOrderRequest = new WxPayUnifiedOrderRequest();

        String randomStr = getRandomNum(18).toUpperCase();
        wxPayUnifiedOrderRequest.setNonceStr(randomStr);

        wxPayUnifiedOrderRequest.setOutTradeNo(order.getSn());
        wxPayUnifiedOrderRequest.setOpenid(member.getOpenId());
        ShopOrderItem shopOrderItem = new ShopOrderItem();
        shopOrderItem.setOrderId(order.getId());
        List<ShopOrderItem> orderGoods = shopOrderItemService.selectShopOrderItemList(shopOrderItem);
        if (null != orderGoods) {
            String body = "支付订单-";
            for (ShopOrderItem goodsVo : orderGoods) {
                body = body + goodsVo.getName() + "、";
            }
            if (body.length() > 0) {
                body = body.substring(0, body.length() - 1);
            }
            // 商品描述
            wxPayUnifiedOrderRequest.setBody(body);
        }
        BigInteger fee = BigDecimal.valueOf(order.getAmount()).multiply(new BigDecimal(100)).toBigInteger();
        wxPayUnifiedOrderRequest.setTotalFee(fee.intValue());
        String notify_url="/api/weixin/notify_pay.jhtml";
        String url = "https://www.wangyoujiuhang.shop" + notify_url;
        wxPayUnifiedOrderRequest.setNotifyUrl(url);
        wxPayUnifiedOrderRequest.setTradeType("JSAPI");
        wxPayUnifiedOrderRequest.setSpbillCreateIp("127.0.0.1");
        try {
            WxPayMpOrderResult result = wxPayService.createOrder(wxPayUnifiedOrderRequest);
            return  ApiResult.success(result);
        } catch (WxPayException e) {
            e.printStackTrace();
            return ApiResult.error("支付订单发生异常");
        }
    }

    //获取请求参数
    @GetMapping("/list")
    @ResponseBody
    public ApiResult list(@RequestParam("current") Integer current,  //当前页数
                          @RequestParam("size") Integer size,    //页面数量
                          @RequestParam("status") Long status    //订单状态
    ) {

        // status : 0, 全部，1 代付款， 2，待使用，3，待收货， 5 待评价
        if(current == null || size == null){
            return ApiResult.error("参数错误,请联系管理员");
        }

        Member member = memberService.getCurrentMember(getRequest());
        if (member == null){
            return ApiResult.error("用户登录过期，请重新尝试");
        }

        Long orderStatus = null;
        if(status == 1){
            orderStatus = Long.valueOf(ShopOrder.Status.pendingPayment.ordinal());
        }else if(status == 2){
            orderStatus = Long.valueOf(ShopOrder.Status.shipped.ordinal());
        }else if(status == 3){
            orderStatus = null; //先给全部
        }else if(status == 5){
            orderStatus = Long.valueOf(ShopOrder.Status.completed.ordinal());
        }

        ShopOrder order = new ShopOrder();
        order.setStatus(orderStatus);
        order.setMemberId(member.getId());
        startPage(current,size,"modify_date");
        List<ShopOrder> shopOrderList = shopOrderService.selectShopOrderList(order);
        JSONObject resultJson = new JSONObject();
        resultJson.put("list", shopOrderList);
        resultJson.put("current", current);
        resultJson.put("pages", current);
        return ApiResult.success(resultJson);
    }

    @GetMapping("/detail")
    @ResponseBody
    public ApiResult detail(@RequestParam("sn") String orderSn) {
        if (orderSn == null){
            return ApiResult.error("参数错误，请联系管理员");
        }

        ShopOrder order = shopOrderService.selectShopOrderBySn(orderSn);
        if (order == null){
            return ApiResult.error("此订单不存在");
        }

        Long businessShopId = order.getBusinessShopId();
        BusinessShop businessShop = businessShopService.selectBusinessShopById(businessShopId);
        if (businessShop == null){
            return ApiResult.error("此商家不存在");
        }
        List<ShopOrderItem> orderItems = order.getShopOrderItems();
        if (orderItems.size() > 1 ||  orderItems.size() == 0){
            return ApiResult.error("订单数据异常");
        }
        ShopOrderItem shopOrderItem = orderItems.get(0);
        Long goodsId = shopOrderItem.getGoodsId();
        Goods goods = goodsService.selectGoodsById(goodsId);
        if (goods == null){
            return ApiResult.error("订单数据异常, 商品已经被删除");
        }
        JSONObject resultJson = new JSONObject();
        resultJson.put("order", order);
        resultJson.put("orderItem", shopOrderItem);
        resultJson.put("shop", businessShop);
        resultJson.put("goods", goods);
//        //生成code 用于核销
//        String code = RandomStringUtils.random(8, "abcdefghijklmnopqrstuvwxyz1234567890");
//        order.setCode(code);
//        shopOrderService.updateShopOrder(order);
        resultJson.put("code", order.getCode());
        return ApiResult.success(resultJson);
    }


    private boolean belongCalendar(Date nowTime, Date beginTime, Date endTime) {
        Calendar date = Calendar.getInstance();
        date.setTime(nowTime);

        Calendar begin = Calendar.getInstance();
        begin.setTime(beginTime);

        Calendar end = Calendar.getInstance();
        end.setTime(endTime);

        return date.after(begin) && date.before(end);
    }

    public String getRandomString(Integer num) {
        String base = "abcdefghijklmnopqrstuvwxyz0123456789";
        Random random = new Random();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < num; i++) {
            int number = random.nextInt(base.length());
            sb.append(base.charAt(number));
        }
        return sb.toString();
    }

    public static String getRandomNum(Integer num) {
        String base = "0123456789";
        Random random = new Random();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < num; i++) {
            int number = random.nextInt(base.length());
            sb.append(base.charAt(number));
        }
        return sb.toString();
    }
}
